package com.dbapp.garden.controller.student;


import com.dbapp.garden.common.*;
import com.dbapp.garden.common.com.dbapp.garden.common.exception.BusinessException;
import com.dbapp.garden.entity.*;
import com.dbapp.garden.service.*;
import com.dbapp.garden.vm.GardenImportBatchVm;
import com.dbapp.garden.vm.GardenStudentInfoVm;
import com.dbapp.garden.vm.StudentInfoSearchVm;
import com.dbapp.garden.vm.StudentUpdateVm;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 学员基础信息 控制器类
 *
 * @author gangzi
 *         2017-10-12
 */
@Controller
public class StudentInfoController {

    private static final Logger log = LoggerFactory.getLogger(StudentInfoController.class);

    private static final String[] FILE_TYPE = {"xls", "xlsx"};

    @Value("${student.excel.path}")
    private String STUDENT_EXCEL_PATH;
    @Autowired
    private GardenStudentInfoService stuService;

    @Autowired
    private GardenStudentAreaService stuAreaService;

    @Autowired
    private GardenStudentImportanceService stuImportanceService;

    @Autowired
    private GardenStudentSourceService stuSourceService;

    @Autowired
    private GardenStudentContactService stuContactService;

    @Autowired
    private GardenStudentStateService stuStateService;

    @Autowired
    private GardenStudentFollowService stuFollowService;

    @Autowired
    private GardenStaffInfoService staffInfoService;

    @Autowired
    private GardenStudentFailService studentFailService;

    @Autowired
    private GardenImportBatchService importBatchService;

    @Autowired
    private GardenInfoService gardenInfoService;

    @GetMapping("/student")
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO')")
    public String toStudentPage(HttpServletRequest request, Model model) {
        Map<String, Object> paramMap = new HashMap<String, Object>(16);
        paramMap.put("areaParentId", 0);

        List<GardenStudentArea> areaList = stuAreaService.getStudentAreaList(paramMap);
        List<GardenStudentImportance> importanceList = stuImportanceService.getStudentImportanceList(paramMap);
        List<GardenStudentSource> sourceList = stuSourceService.getStudentSourceList(paramMap);
        List<GardenStudentContact> contactList = stuContactService.getStudentContactList(paramMap);
        List<GardenStudentState> stateList = stuStateService.getStudentStateList(paramMap);
        List<GardenStudentFollow> followList = stuFollowService.getStudentFollowList(paramMap);
        // 获取接待人
        List<GardenStaffInfo> receptionist = staffInfoService.getStaffList(paramMap);
        // 获取市场人员
        paramMap.clear();
        paramMap.put("isMarketPerson", 1);
        List<GardenStaffInfo> marketPersonList = staffInfoService.getStaffList(paramMap);
        // 获取所属顾问
        paramMap.clear();
        paramMap.put("isAdviser", 1);
        List<GardenStaffInfo> adviserList = staffInfoService.getStaffList(paramMap);

        paramMap.clear();
        List<GardenInfo> gardens=gardenInfoService.getGardenList(paramMap);

        model.addAttribute("areaList", areaList);
        model.addAttribute("importanceList", importanceList);
        model.addAttribute("sourceList", sourceList);
        model.addAttribute("contactList", contactList);
        model.addAttribute("stateList", stateList);
        model.addAttribute("followList", followList);
        model.addAttribute("receptionist", receptionist);
        model.addAttribute("marketPersonList", marketPersonList);
        model.addAttribute("adviserList", adviserList);
        model.addAttribute("gardens", gardens);
        return "student/studentlist";
    }

    @PostMapping("/studentlist")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO')")
    public Map<String, ?> studentList(HttpServletRequest request, String param, StudentInfoSearchVm searchVm) {
        log.info("接收的请求参数是：" + param);

        Map<String, Object> paramMap = DataTableUtils.parseParam(param);
        if (paramMap == null) {
            return RenderJSON.makeMap(-1, "参数不合法！", null, "");
        }
        String sEcho = (String) paramMap.get("sEcho");
        String sSearch = (String) paramMap.get("sSearch");
        int iDisplayStart = (int) paramMap.get("iDisplayStart");
        int iDisplayLength = (int) paramMap.get("iDisplayLength");

        paramMap.clear();

        paramMap.put("start", iDisplayStart);
        paramMap.put("limit", iDisplayLength);
        //设置签约状态，只有已经签约的学员才显示在"学员核心资料管理"
        paramMap.put("signStatus",1);
        //学员姓名
        if (StringUtils.isNotBlank(searchVm.getStuName())){
            paramMap.put("search", searchVm.getStuName());
        }
        //学员性别
        if (searchVm.getStuSex() != null && searchVm.getStuSex() >= 1) {
            paramMap.put("stuSex", searchVm.getStuSex());
        }
        //学员状态
        if (searchVm.getStuStatus()!=null&&searchVm.getStuStatus()>0){
            paramMap.put("stuState",searchVm.getStuStatus());
        }
        //学员生日
        if (StringUtils.isNotBlank(searchVm.getBirthFrom())){
            paramMap.put("birthFrom",searchVm.getBirthFrom());
        }
        if (StringUtils.isNotBlank(searchVm.getBirthTo())){
            paramMap.put("birthTo",searchVm.getBirthTo());
        }

        //所属幼儿园
        List<GardenStudentInfo> studentList = stuService.getStudentList(paramMap);
        Integer count = stuService.getStudentCount(paramMap);

        return RenderJSON.makePagenateMap(1, "获取成功", sEcho, count, count, studentList, "");
    }

    @PutMapping("/student/{id}")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO_EDIT')")
    public Map<String, ?> editStudent(HttpServletRequest request, @PathVariable("id") Integer id,
                                      @RequestBody @Valid GardenStudentInfoVm stuInfoVm) {
        GardenStudentInfo stuInfo = stuService.findById(id);
        if (stuInfo == null) {
            return RenderJSON.makeStandMap(1, "对不起，该学生不存在，编辑失败！", "error");
        }
        stuInfo.setStuName(stuInfoVm.getStuName());
        stuInfo.setStuPhone(stuInfoVm.getStuPhone());
        Integer result = stuService.save(stuInfo);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }

    }

    @GetMapping("/student/{id}")
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO_VIEW')")
    public String toStudentViewPage(HttpServletRequest request, @PathVariable("id") Integer id, Model model) {
        GardenStudentInfo student = stuService.findById(id);

        model.addAttribute("student", student);
        return "student/studentview";
    }

    @GetMapping("/studentedit/{id}")
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO_EDIT')")
    public String toStudentEditPage(HttpServletRequest request, @PathVariable("id") Integer id, Model model) {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("areaParentId", 0);
        List<GardenStudentArea> areaList = stuAreaService.getStudentAreaList(paramMap);
        List<GardenStudentImportance> importanceList = stuImportanceService.getStudentImportanceList(paramMap);
        List<GardenStudentSource> sourceList = stuSourceService.getStudentSourceList(paramMap);
        List<GardenStudentContact> contactList = stuContactService.getStudentContactList(paramMap);
        List<GardenStudentState> statetList = stuStateService.getStudentStateList(paramMap);
        List<GardenStudentFollow> followList = stuFollowService.getStudentFollowList(paramMap);
        // 获取接待人
        List<GardenStaffInfo> receptionist = staffInfoService.getStaffList(paramMap);
        // 获取市场人员
        paramMap.clear();
        paramMap.put("isMarketPerson", 1);
        List<GardenStaffInfo> marketPersonList = staffInfoService.getStaffList(paramMap);
        // 获取所属顾问
        paramMap.clear();
        paramMap.put("isAdviser", 1);
        List<GardenStaffInfo> adviserList = staffInfoService.getStaffList(paramMap);
        GardenStudentInfo student = stuService.findById(id);

        model.addAttribute("areaList", areaList);
        model.addAttribute("importanceList", importanceList);
        model.addAttribute("sourceList", sourceList);
        model.addAttribute("contactList", contactList);
        model.addAttribute("stateList", statetList);
        model.addAttribute("followList", followList);
        model.addAttribute("student", student);
        model.addAttribute("receptionist", receptionist);
        model.addAttribute("marketPersonList", marketPersonList);
        model.addAttribute("adviserList", adviserList);
        return "student/studentedit";
    }

    @PutMapping("/studentedit/{id}")
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO_EDIT')")
    @ResponseBody
    public Map<String, ?> editStudentSave(HttpServletRequest request, @PathVariable("id") Integer id,
                                          @RequestBody @Valid GardenStudentInfoVm stuInfoVm) {
        GardenStudentInfo stuInfo = stuService.findById(id);
        if (stuInfo == null) {
            return RenderJSON.makeStandMap(1, "对不起，该学员不存在", "error");
        }
        // stuInfo.setStuName(stuInfoVm.getStuName());
        // stuInfo.setStuNickName(stuInfoVm.getStuNickName());
        // stuInfo.setStuBirth(stuInfoVm.getStuBirth());
        // stuInfo.setStuSex(stuInfoVm.getStuSex());
        // stuInfo.setStuPhone(stuInfoVm.getStuPhone());
        // stuInfo.setStuParentName(stuInfoVm.getStuParentName());
        // stuInfo.setStuParentRelationship(stuInfoVm.getStuParentRelationship());
        // stuInfo.setStuBackupPhone(stuInfoVm.getStuBackupPhone());
        // stuInfo.setStuQq(stuInfoVm.getStuQq());
        // stuInfo.setStuTelephone(stuInfoVm.getStuTelephone());
        // stuInfo.setStuEmail(stuInfoVm.getStuEmail());
        // stuInfo.setStuAreaFirst(stuInfoVm.getStuAreaFirst());
        // stuInfo.setStuAreaSecond(stuInfoVm.getStuAreaSecond());
        // stuInfo.setStuWechatName(stuInfoVm.getStuWechatName());
        // stuInfo.setStuHomeAddress(stuInfoVm.getStuHomeAddress());
        try {
            BeanUtils.copyProperties(stuInfo, stuInfoVm);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }
        stuInfo.setId(id);
        stuInfo.setUpdateTime(new Date());
        Integer result = stuService.save(stuInfo);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }
    }

    @PostMapping("/studentadd")
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO_ADD')")
    @ResponseBody
    public Map<String, ?> addStudentSave(HttpServletRequest request, @RequestBody @Valid GardenStudentInfoVm stuInfoVm) {

        GardenStudentInfo stuInfo = new GardenStudentInfo();
        stuInfo.setStuName(stuInfoVm.getStuName());
        stuInfo.setStuNickName(stuInfoVm.getStuNickName());
        stuInfo.setStuBirth(stuInfoVm.getStuBirth());
        stuInfo.setStuSex(stuInfoVm.getStuSex());
        stuInfo.setStuPhone(stuInfoVm.getStuPhone());
        stuInfo.setStuParentName(stuInfoVm.getStuParentName());
        stuInfo.setStuParentRelationship(stuInfoVm.getStuParentRelationship());
        stuInfo.setStuBackupPhone(stuInfoVm.getStuBackupPhone());
        stuInfo.setStuQq(stuInfoVm.getStuQq());
        stuInfo.setStuTelephone(stuInfoVm.getStuTelephone());
        stuInfo.setStuEmail(stuInfoVm.getStuEmail());
        stuInfo.setStuAreaFirst(stuInfoVm.getStuAreaFirst());
        stuInfo.setStuAreaSecond(stuInfoVm.getStuAreaSecond());
        stuInfo.setStuWechatName(stuInfoVm.getStuWechatName());
        stuInfo.setStuHomeAddress(stuInfoVm.getStuHomeAddress());
        stuInfo.setStuSource(stuInfoVm.getStuSource());
        stuInfo.setStuMarketPerson(stuInfoVm.getStuMarketPerson());
        stuInfo.setStuImportance(stuInfoVm.getStuImportance());
        stuInfo.setStuIntentionCourse(stuInfoVm.getStuIntentionCourse());
        stuInfo.setStuCurrentClass(stuInfoVm.getStuCurrentClass());
        stuInfo.setStuState(stuInfoVm.getStuState());
        stuInfo.setStuFirstContact(stuInfoVm.getStuFirstContact());
        stuInfo.setStuJoinDate(stuInfoVm.getStuJoinDate());
        stuInfo.setStuBasicInfo(stuInfoVm.getStuBasicInfo());
        stuInfo.setStuGroup(stuInfoVm.getStuGroup());
        stuInfo.setStuReceptionist(stuInfoVm.getStuReceptionist());
        stuInfo.setStuCurrentScore(stuInfoVm.getStuCurrentScore());
        stuInfo.setStuFollowStyle(stuInfoVm.getStuFollowStyle());
        stuInfo.setStuSchool(stuInfoVm.getStuSchool());
        stuInfo.setCreateTime(new Date());
        stuInfo.setUpdateTime(new Date());
        Integer result = stuService.save(stuInfo);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，添加成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，添加失败！", "error");
        }
    }

    @PostMapping("/studentdelete")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO_DELETE')")
    public Map<String, ?> deleteStudent(HttpServletRequest request, @RequestBody Integer[] ids) {

        if (ids == null) {
            return RenderJSON.makeStandMap(1, "对不起，提交参数错误！", "error");
        }

        Integer result = stuService.batchDeleteStudent(ids);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，删除成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，删除失败！", "error");
        }

    }

    @PutMapping("/studentmarket")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_STUDENT_INFO_EDIT')")
    public Map<String, ?> editStudentMarketperson(HttpServletRequest request, @RequestBody @Valid StudentUpdateVm updateVm) {

        Integer[] ids = updateVm.getIds();
        Integer personId = updateVm.getPersonId();
        if (ids == null) {
            return RenderJSON.makeStandMap(1, "对不起，提交参数错误！", "error");
        }

        List<GardenStudentInfo> studentInfos = stuService.getStudentByIds(ids);
        List<GardenStudentInfo> readyToUpdate = studentInfos.stream().map(s -> {
            log.info("查询到的ID：" + s.getId());
            s.setStuMarketPerson(personId);
            s.setUpdateTime(new Date());
            return s;
        }).collect(Collectors.toList());

        Integer result = stuService.batchUpdateStudent(readyToUpdate);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，更新成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，更新失败！", "error");
        }

    }

    @GetMapping("/download_template")
    public void downloadTemplate(String[] ids, HttpServletResponse response) {
        if (ids == null && ids.length <= 0) {
            throw new BusinessException("模版参数为空，请检查");
        }
        DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String fileName = "student_" + LocalDateTime.now().format(f).toString() + ".xlsx";

        log.info("fileName=" + fileName);
        response.reset();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }


        String[] parent = {"爸爸", "妈妈", "爷爷", "奶奶", "哥哥", "姐姐", "叔叔", "阿姨"};
        String[] sex = {"男", "女"};
        String[] market = getMarketPerson();
        String[] adviser = getAdviser();
        String[] state = getStudentState();
        String[] source = getStudentSource();
        String[] contact = getFirstContact();
//        String[] currentClass = getCurrentClass();
        String[] importance = getImportance();
        String[] follow = getFollowStyle();
        Map<String, String[]> dropdownData = new HashMap<>(16);
        dropdownData.put("4", parent);
        dropdownData.put("7", sex);
        dropdownData.put("14", market);
        dropdownData.put("15", adviser);
        dropdownData.put("16", state);
        dropdownData.put("17", source);
        dropdownData.put("18", contact);
//        dropdownData.put("19", currentClass);
        dropdownData.put("22", importance);
        dropdownData.put("29", follow);
        XSSFWorkbook workbook = ExcelUtils.generateTemplate(ids, dropdownData);

        try {
            workbook.write(outputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }


        try {
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        IOUtils.closeQuietly(outputStream);

    }

    @PostMapping("/import_student_info")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, ?> batchImportStudent(HttpServletRequest request, GardenImportBatchVm batchVm) throws Exception {

        String excel_path = uploadExcel(request, STUDENT_EXCEL_PATH);

        Workbook wb = new XSSFWorkbook(new FileInputStream(excel_path));
        List<GardenStudentInfo> readyToInsertList = new ArrayList<>();
        List<GardenStudentInfo> phoneExistList = new ArrayList<>();
        List<GardenStudentInfo> phoneErrorList = new ArrayList<>();
        List<GardenStudentInfo> excelStudentList = ExcelUtils.getDataFromExcel(wb);

        excelStudentList.stream().forEach(xStudent -> {
            String phone = xStudent.getStuPhone();
            if (StringUtils.isNotBlank(phone)) {
                boolean isPhone = PhoneNumberUtils.isMobileNumber(phone);
                //校验手机号码格式
                if (!isPhone) {
                    phoneErrorList.add(xStudent);
                } else {
                    Map<String, Object> map = new HashMap<>(16);
                    map.put("stuPhone", phone);
                    List<GardenStudentInfo> infos = stuService.getStudentList(map);
                    //手机号码正确，并且不存在
                    if (infos == null || infos.isEmpty()) {
                        readyToInsertList.add(xStudent);
                    } else {
                        //号码已存在
                        phoneExistList.add(xStudent);
                    }
                }

            } else {
                readyToInsertList.add(xStudent);
            }
        });

        //学员入库
        Integer result = stuService.batchInsertStudent(readyToInsertList);
        //生成导入批次
        GardenImportBatch importBatch = new GardenImportBatch();
        importBatch.setBatchCount(excelStudentList.size());
        importBatch.setBatchName(batchVm.getBatchName());
        importBatch.setBatchSource(batchVm.getBatchSource());
        importBatch.setRepeatFail(phoneExistList.size());
        importBatch.setOtherFail(phoneErrorList.size());
        importBatch.setCreateTime(new Date());
        importBatch.setUpdateTime(new Date());
        importBatch.setBatchSuccess(readyToInsertList.size());

        Integer r = importBatchService.save(importBatch);


        //封装失败名单
        List<GardenStudentFail> failList = mergeFailList(importBatch.getId(), phoneExistList, phoneErrorList);

        //封装成功学生名单


        //插入导入失败学生名单
        Integer failResult = studentFailService.batchInsert(failList);

        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "批量导入成功", "");
        } else {
            return RenderJSON.makeStandMap(0, "批量导入失败", "");
        }

    }

    private List<GardenStudentFail> mergeFailList(Integer batchId, List<GardenStudentInfo> phoneExistList, List<GardenStudentInfo> phoneErrorList) {
        List<GardenStudentFail> failList = new ArrayList<>();
        phoneErrorList.stream().forEach(s -> {
            GardenStudentFail fail = new GardenStudentFail();
            fail.setCreateTime(new Date());
            fail.setUpdateTime(new Date());
            fail.setStuFailReason(2);
            fail.setStuPhone(s.getStuPhone());
            fail.setStuName(s.getStuName());
            fail.setStuParentName(s.getStuParentName());
            fail.setStuParentRelationship(s.getStuParentRelationship());
            fail.setStuNickname(s.getStuNickName());
            fail.setBatchId(batchId);
            failList.add(fail);
        });

        phoneExistList.stream().forEach(s -> {
            GardenStudentFail fail = new GardenStudentFail();
            fail.setCreateTime(new Date());
            fail.setUpdateTime(new Date());
            fail.setStuFailReason(1);
            fail.setStuPhone(s.getStuPhone());
            fail.setStuName(s.getStuName());
            fail.setStuParentName(s.getStuParentName());
            fail.setStuParentRelationship(s.getStuParentRelationship());
            fail.setStuNickname(s.getStuNickName());
            fail.setBatchId(batchId);
            failList.add(fail);
        });

        return failList;
    }


    /**
     * 上传Excel
     *
     * @param request
     * @param student_excel_path
     * @return
     */
    private String uploadExcel(HttpServletRequest request, String student_excel_path) {
        String result = "";
        if ((request instanceof MultipartHttpServletRequest)) {
            String fileType;
            // 创建文件夹
            File filepath = new File(student_excel_path);
            if (!filepath.exists()) {
                filepath.mkdirs();
            }
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
            Iterator<String> filenames = mRequest.getFileNames();
            if (filenames != null && filenames.hasNext()) {
                while (filenames.hasNext()) {
                    String inputFileName = filenames.next();
                    if (StringUtils.isEmpty(inputFileName)) {
                        continue;
                    }
                    List<MultipartFile> files = mRequest.getFiles(inputFileName);
                    for (MultipartFile file : files) {
                        if (file == null) {
                            continue;
                        }
                        String originalFilename = file.getOriginalFilename();
                        System.out.println("原始文件名是：" + originalFilename);
                        fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                        if (!FileTypeUtils.EXCEL_FILE_TYPE.contains(fileType)) {
                            throw new BusinessException("请上传正确的文件类型！");
                        }
                        String fName = originalFilename.substring(0, originalFilename.lastIndexOf(".")) + System.currentTimeMillis() + "." + fileType;
                        String localFile = student_excel_path + File.separator + fName;
                        try (FileOutputStream fs = new FileOutputStream(localFile); InputStream stream = file.getInputStream()) {
                            byte[] buffer = new byte[1024 * 1024];
                            int byteRead;
                            while ((byteRead = stream.read(buffer)) != -1) {
                                fs.write(buffer, 0, byteRead);
                                fs.flush();
                            }

                            result = localFile;

                        } catch (Exception e) {
                            throw new BusinessException("文件上传失败！");
                        }
                    }
                }
            }
        }
        return result;
    }

    private String[] getFollowStyle() {
        Map<String, Object> map = new HashMap<>(16);
        List<GardenStudentFollow> contactList = stuFollowService.getStudentFollowList(map);
        List<String> stringList = contactList.stream().map(c -> c.getFollowDesc() + "=" + c.getId()).collect(Collectors.toList());
        return stringList.toArray(new String[stringList.size()]);
    }

    private String[] getImportance() {
        Map<String, Object> map = new HashMap<>(16);
        List<GardenStudentImportance> contactList = stuImportanceService.getStudentImportanceList(map);
        List<String> stringList = contactList.stream().map(c -> c.getImportanceParam() + "=" + c.getId()).collect(Collectors.toList());
        return stringList.toArray(new String[stringList.size()]);
    }

//    private String[] getCurrentClass() {
//
//    }

    private String[] getFirstContact() {
        Map<String, Object> map = new HashMap<>(16);
        List<GardenStudentContact> contactList = stuContactService.getStudentContactList(map);
        List<String> stringList = contactList.stream().map(c -> c.getContactParam() + "=" + c.getId()).collect(Collectors.toList());
        return stringList.toArray(new String[stringList.size()]);
    }

    private String[] getStudentSource() {
        Map<String, Object> map = new HashMap<>(16);
        List<GardenStudentSource> contactList = stuSourceService.getStudentSourceList(map);
        List<String> stringList = contactList.stream().map(c -> c.getSourceName() + "=" + c.getId()).collect(Collectors.toList());

        return stringList.toArray(new String[stringList.size()]);
    }

    private String[] getStudentState() {
        Map<String, Object> map = new HashMap<>(16);
        List<GardenStudentState> stateList = stuStateService.getStudentStateList(map);
        List<String> stringList = stateList.stream().map(s -> s.getStateParam() + "=" + s.getId()).collect(Collectors.toList());
        return stringList.toArray(new String[stateList.size()]);

    }


    private String[] getAdviser() {
        Map<String, Object> map = new HashMap<>(16);
        map.put("isAdviser", 1);
        List<GardenStaffInfo> marketPerson = staffInfoService.getStaffList(map);
        List<String> marketName = marketPerson.stream().map(p -> p.getStaffRealName() + "==" + p.getId()).collect(Collectors.toList());

        return marketName.toArray(new String[marketName.size()]);
    }

    private String[] getMarketPerson() {
        Map<String, Object> map = new HashMap<>(16);
        map.put("isMarketPerson", 1);
        List<GardenStaffInfo> marketPerson = staffInfoService.getStaffList(map);
        List<String> marketName = marketPerson.stream().map(p -> p.getStaffRealName() + "==" + p.getId()
        ).collect(Collectors.toList());

        return marketName.toArray(new String[marketName.size()]);
    }

    @GetMapping("/photo")
    public String toPhoto(HttpServletRequest request) {
        return "student/photo";
    }
}
